/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.iwords.teacher.web;

import com.iwords.ejb.SchoolFacade;
import com.iwords.ejb.entity.School;
import com.iwords.service.object.TeacherEntity;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import javax.ejb.EJB;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.ImageIcon;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author yunzi
 */
@WebServlet(name = "ImageServlet", urlPatterns = {"/image"})
public class ImageServlet extends BaseServlet {

    public void form(HttpServletRequest request, HttpServletResponse response) throws Exception {
        forward(request, response, "/image/form.jsp");
    }

    /**
     * 图片上传后，依照下列命名规则处理：
     * 1. 原生图片存储在webapp/images/temp/下
     * 2. 封面图片，命名格式为 cover_menuId_landscape.xxx 及 cover_menuId_portrait.xxx
     * 3. 菜品图片，命名格式为 course_courseId_landscape.xxx 及 course_courseId_portrait.xxx
     */
    public void upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        boolean isMultipart = ServletFileUpload.isMultipartContent(httpRequest);
        System.out.println("ImageServlet.upload() isMultipart = " + isMultipart);
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Set factory constraints
        int maxMemorySize = ImageConfig.IMAGE_MEMORY_MAX;
        int maxImageSize = ImageConfig.IMAGE_SIZE_MAX;
        factory.setSizeThreshold(maxMemorySize * 1024 * 1024);//max memory size in bytes
        factory.setRepository(new java.io.File(ImageConfig.IMAGE_TEMP_DIR));//temp directory 

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Set overall request size constraint
        upload.setSizeMax(maxImageSize * 1024 * 1024);

        // Parse the request
        //the only FileItem
        FileItem fileItem = null;
        List<FileItem> items = upload.parseRequest(httpRequest);
        Iterator<FileItem> iter = items.iterator();
        System.out.println("response.isCommitted() 3 = "+response.isCommitted());
        while (iter.hasNext()) {
            FileItem item = iter.next();

            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString();
                System.out.println("LandscapeImageBean.upload() ............ name=" + name + " value=" + value);
                if ("???".equals(name)) {
                    
                }
            } else {
                fileItem = item;
            }
        }
        if (fileItem == null) {
            error(request, response, "参数错误，图片上传失败。");
            return ;
        }
        String fieldName = fileItem.getFieldName();
        String fileName = fileItem.getName();
        String contentType = fileItem.getContentType();
        boolean isInMemory = fileItem.isInMemory();
        long sizeInBytes = fileItem.getSize();
        String extension = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        System.out.println("LandscapeImageBean.upload() extension = "+extension);
        TeacherEntity teacher = (TeacherEntity) request.getSession(true).getAttribute("teacherInSession");
        String path = ImageConfig.IMAGE_TEMP_DIR + "/"+ teacher.getSchoolId() + extension;//?????


        System.out.println("response.isCommitted() 2 = "+response.isCommitted());
        System.out.println("LandscapeImageBean.upload() path = " + path);
        System.out.println("LandscapeImageBean.upload() fieldName = " + fieldName);
        System.out.println("LandscapeImageBean.upload() fileName = " + fileName);
        System.out.println("LandscapeImageBean.upload() contenType = " + contentType);
        System.out.println("LandscapeImageBean.upload() isInMemory = " + isInMemory);
        System.out.println("LandscapeImageBean.upload() sizeInBytes = " + sizeInBytes);
        File uploadedFile = new File(path);
        if (!uploadedFile.exists()) {
            uploadedFile.getParentFile().mkdirs();
        }
        System.out.println("response.isCommitted() 1 = "+response.isCommitted());
        fileItem.write(uploadedFile);
        System.out.println("response.isCommitted() 0 = "+response.isCommitted());
        ImageIcon image = new ImageIcon(path);
        int width = image.getIconWidth();
        int height = image.getIconHeight();
        request.setAttribute("image", teacher.getSchoolId() + extension);
        request.setAttribute("width", width);
        request.setAttribute("height", height);
        forward(request, response, "/image/preview.jsp");
    }
    
    @EJB
    SchoolFacade schoolFacade;
    public void saveImageInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String imageName = request.getParameter("imageName");
        System.out.println("imageName = " + imageName);
        TeacherEntity teacher = (TeacherEntity) request.getSession(true).getAttribute("teacherInSession");
        School school = schoolFacade.find(teacher.getSchoolId());
        school.setLogo(imageName);
        schoolFacade.edit(school);
        //将图片从temp目录拷贝到正式目录
        String path = ImageConfig.IMAGE_TEMP_DIR + "/" + imageName;
        System.out.println("ImageServlet.saveImageInfo() from path = "+path);
        File file = new File(path);
        String pathTo = ImageConfig.IMAGE_DIR + "/" + imageName;
        System.out.println("ImageServlet.saveImageInfo() to path = "+pathTo);
        file.renameTo(new File(pathTo));
        //保存成功，则返回
        forward(request, response, "/student");
    }
}
